{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 归并排序算法"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 38,
   "metadata": {},
   "outputs": [],
   "source": [
    "def Union(L1, L2):\n",
    "    '''\n",
    "    Union two ordered list.\n",
    "    '''\n",
    "    i = 0\n",
    "    j = 0\n",
    "    L = []\n",
    "    while i < len(L1) and j < len(L2):\n",
    "        if L1[i] <= L2[j]:\n",
    "            L.append(L1[i])\n",
    "            i += 1\n",
    "        elif L1[i] > L2[j]:\n",
    "            L.append(L2[j])\n",
    "            j += 1\n",
    "        \n",
    "    L = L + L1[i:] + L2[j:]\n",
    "    return L"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 39,
   "metadata": {},
   "outputs": [],
   "source": [
    "def Merge_sort(L,p,r):\n",
    "    '''\n",
    "    Input:\n",
    "    - L: a unordered list\n",
    "    - p: the start index\n",
    "    - r: the end index\n",
    "    Output:\n",
    "    - L: a ordered list.\n",
    "    '''\n",
    "    if p > r:\n",
    "        print('Error input.')\n",
    "        return L\n",
    "    if r - p == 0:\n",
    "        return [L[p]]\n",
    "    if r - p == 1:\n",
    "        if L[r] < L[p]:\n",
    "            L[r], L[p] = L[p], L[r]\n",
    "        return [L[p], L[r]]\n",
    "    q = int((p + r) / 2)\n",
    "    left = Merge_sort(L,p,q)\n",
    "    right = Merge_sort(L,q+1,r)\n",
    "    return Union(left,right)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 40,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[1, 1, 3, 6, 9, 41]\n"
     ]
    }
   ],
   "source": [
    "# running this to check the algorithm\n",
    "L = [1,3,41,1,9,6]\n",
    "print(Merge_sort(L,0,len(L)-1))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "torch",
   "language": "python",
   "name": "torch"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
